#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>

#define DEVNAME "/dev/mycdev_simple0"

#define IOCTL_MODE_MAGIC 'x'
#define IOCTL_MODE_1 _IO(IOCTL_MODE_MAGIC, 1)
#define IOCTL_MODE_2 _IO(IOCTL_MODE_MAGIC, 2)


int main(void)
{
    int devfd, i, j, retval;
    char buff[] = "1234567890";
    char readbuff[64] = {0};


    devfd = open(DEVNAME, O_RDWR);
    if (devfd == -1) {
        printf("open %s failed\n", DEVNAME);
        return 0;
    }
    
    retval = write(devfd, buff, strlen(buff));
    if(retval == -1) {
        printf("write to %s failed, %s\n", DEVNAME, buff);
        close(devfd);
        return 0;
    }

    memset(readbuff, 0, 64);
    retval = read(devfd, readbuff, 64);
    if(retval == -1) {
        printf("read from %s failed\n", DEVNAME);
        close(devfd);
        return 0;
    }

    printf("origin data:%s\n", buff);
    printf("read from %s success: %s,ret=%d\n", DEVNAME, readbuff, retval);

    printf("mode 1: inverted order; mode 2: order;\n");
    retval = ioctl(devfd, IOCTL_MODE_1);
    if(retval == -1) {
        printf("ioctl %s failed\n", DEVNAME);
        close(devfd);
        return 0;
    }
    
    memset(readbuff, 0, 64);
    retval = read(devfd, readbuff, 64);
    if(retval == -1) {
        printf("after IOCTL_MODE_1, read from %s failed\n", DEVNAME);
        close(devfd);
        return 0;
    }
    printf("after IOCTL_MODE_1, read from %s success: %s\n", DEVNAME, readbuff);

    retval = ioctl(devfd, IOCTL_MODE_2);
    if(retval == -1) {
        printf("ioctl %s failed\n", DEVNAME);
        close(devfd);
        return 0;
    }

    memset(readbuff, 0, 64);
    retval = read(devfd, readbuff, 64);
    if(retval == -1) {
        printf("after IOCTL_MODE_2, read from %s failed\n", DEVNAME);
        close(devfd);
        return 0;
    }
    printf("after IOCTL_MODE_2, read from %s success: %s\n", DEVNAME, readbuff);

   
    close(devfd);


    return 0;
}
